<?php
/**
 * Created by PhpStorm.
 * User: tandunzhao
 * Date: 2018/5/28
 * Time: 上午10:57
 */

namespace App\Libs\Pay\Merchants;


use App\Libs\Pay\Marchent;
use EasyWeChat\Factory;
use Log;
use DB;

class OfficialPay implements Marchent
{

    private $appid;
    private $secret;
    private $token;
    private $merchant_id;
    private $key;
    private $cert_path;
    private $key_path;
    public $app;

    function setConfig($config) {
        $this->appid = $config['appid'];
        $this->secret = $config['secret'];
        $this->token = $config['token'];
        $this->merchant_id = $config['merchant_id'];
        $this->key = $config['key'];
        $this->cert_path = $config['cert_path'];
        $this->key_path = $config['key_path'];

        $options = [
            'app_id'=>$this->appid,
            'mch_id'=>$this->merchant_id,
            'key'=>$this->key,
            'cert_path'=>$this->cert_path,
            'key_path'=>$this->key_path,
            //'notify_url'=>$this->notify_url,
        ];
        $this->app = Factory::payment($options);
        //$this->app->setSubMerchant('sub-merchant-id', 'sub-app-id');  // 子商户 AppID 为可选项
    }


    function send($data)
    {
        Log::info('微信支付下单--Official---enter--start------------');
        $app =  $this->app;
        $paymentData = [
            'body' => $data['body'],
            'out_trade_no' => $data['trade_no'],
            'total_fee' => $data['price'],
            'spbill_create_ip' => $data['create_ip'], // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
            'notify_url' => $data['notify_url'], // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $data['openid'],

            'detail' => $data['detail'],
            'attach' => $data['remark'],
        ];
        try {
            $result = $app->order->unify($paymentData);
            /*
             * "return_code" => "SUCCESS"
             *  "return_msg" => "OK"
             *  "appid" => "wx0bbe95edd2d5c47e"
             *  "mch_id" => "1504775411"
             *  "nonce_str" => "MP3MEohbLetdLTPh"
             *  "sign" => "6F49524FE787C4AE3A90CE756B3794E7"
             *  "result_code" => "SUCCESS"
             *  "prepay_id" => "wx29171105094170eec5676e594169975931"
             *  "trade_type" => "JSAPI"
             */

            Log::info('微信支付下单--Official---enter--end------------');
            Log::info('微信支付下单'.json_encode($result));
            Log::info('微信支付下单--Official---enter--end------------');
            if($result
                && isset($result['return_code'])
                && isset($result['result_code'])
                && $result['return_code'] == 'SUCCESS'
                && $result['result_code'] == 'SUCCESS') {
                $dataRe = [
                    'appId' => $result['appid'],
                    'package' => 'prepay_id=' . $result['prepay_id'],
                    'nonceStr' => $result['nonce_str'],
                    'timeStamp' => "".time(),
                    'signType' => 'MD5',
                ];
                $dataRe['paySign'] = MakeSign($dataRe, $this->key);
                return $dataRe;
            }
        } catch (\Exception $e) {
            Log::error('微信支付下单--Official---enter--end------------'.$e);
        }
        return [];
    }

    public function handlePaidObj() {
        return $this->app;
    }


    /**
     * @param $trade_no 商户系统内部的订单号
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    function queryByOutTradeNumber($trade_no) {
        $app =  $this->app;
        try {
            $result = $app->order->queryByOutTradeNumber($trade_no);
            return $result;
        } catch (\Exception $e) {
            Log::error('商户系统内部的订单号------------' . $e);
        }
        //$app->order->queryByOutTradeNumber("商户系统内部的订单号（out_trade_no）");
        return false;
    }

    /**
     * @param $transaction_id 微信订单号
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    function queryByTransactionId($transaction_id) {
        $app =  $this->app;
        try {
            $result = $app->order->queryByTransactionId($transaction_id);
            return $result;
        } catch (\Exception $e) {
            Log::error('微信订单号------------' . $e);
        }
        //$app->order->queryByTransactionId("微信订单号（transaction_id）");
        return false;
    }


    /**
     * 企业付款到用户零钱
     * @param $data
     * @return array
     */
    function payToPerson($data) {
        Log::info('微信企业付款--Official---enter--start------------');
        $app =  $this->app;
        $paymentData = [
            'partner_trade_no' => $data['trade_no'], // 商户订单号，需保持唯一性(只能是字母或者数字，不能包含有符号)
            'openid' => $data['openid'],
            'check_name' => 'NO_CHECK', // NO_CHECK：不校验真实姓名, FORCE_CHECK：强校验真实姓名
            're_user_name' => $data['person_name'], // 如果 check_name 设置为FORCE_CHECK，则必填用户真实姓名
            'amount' => $data['amount'], // 企业付款金额，单位为分
            'desc' => $data['desc'], // 企业付款操作说明信息。必填
        ];
        try {
            $result = $app->transfer->toBalance($paymentData);
            Log::info('微信企业付款--Official---enter--end------------');
            Log::info('微信企业付款'.json_encode($result));
            Log::info('微信企业付款--Official---enter--end------------');
            return $result;
        } catch (\Exception $e) {
            Log::error('微信企业付款--Official---enter--end------------' . $e);
        }
        return [];
    }

    /**
     * 查询付款到零钱的订单
     * @param $trade_no
     * @return array|\EasyWeChat\Kernel\Support\Collection|object|\Psr\Http\Message\ResponseInterface|string
     */
    function queryBalanceOrder($trade_no) {
        $app =  $this->app;
        try {
            $result = $app->transfer->queryBalanceOrder($trade_no);
            return $result;
        } catch (\Exception $e) {
            Log::error('查询付款到零钱的订单--Official---enter--end------------' . $e);
        }
        return false;
    }


    /**
     * 根据商户订单号退款
     * @param string $number 商户订单号
     * @param string $refundNumber 商户退款单号
     * @param int $totalFee 、订单金额
     * @param int $refundFee 退款金额
     * @param array $config
     * @return array
     */
    function byOutTradeNumber(string $number, string $refundNumber, int $totalFee, int $refundFee, array $config = []) {
        Log::info('微信退款--Official---enter--start------------'.$number);
        $app =  $this->app;
        // Example:
        try {
            $result = $app->refund->byOutTradeNumber($number, $refundNumber, $totalFee, $refundFee, $config);
            Log::info('微信退款--Official---enter--end------------');
            Log::info('微信退款'.json_encode($result));
            Log::info('微信退款--Official---enter--end------------');
            return $result;
        } catch (\Exception $e) {
            Log::error('微信退款--Official---enter--end------------' . $e);
        }
        Log::info('微信退款--Official---enter--end------------return []' );
        return [];
    }
}